package com.sugon.stream;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;


public class ProAndCon {
    public static void main(String[] args) {
        LinkedBlockingDeque sharedQueue = new LinkedBlockingDeque();
        ArrayBlockingQueue array = new ArrayBlockingQueue(10);
        Thread prod = new Thread(new Producer(sharedQueue));
        Thread con = new Thread(new Consumer(sharedQueue));

        prod.start();
        con.start();
    }
}

class Producer implements Runnable {
    //
    private final BlockingQueue sharedQueue;

    public Producer(BlockingQueue sharedQueue) {
        this.sharedQueue = sharedQueue;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                System.out.println("produce" + i);
                //把an Object加到BlockingQueue里,如果BlockQueue没有空间,则调用此方法的线程被阻断
                sharedQueue.put(i);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
            }
        }
    }
}

class Consumer implements Runnable {
    //定义一个阻塞队列
    private final BlockingQueue sharedQueue;
    private boolean flag = true;

    public Consumer(BlockingQueue sharedQueue) {
        this.sharedQueue = sharedQueue;
    }

    @Override
    public void run() {
        while (flag) {
            try {
                //取走BlockingQueue里排在首位的对象,若BlockingQueue为空,阻断进入等待状态直到
                //BlockingQueue有新的数据被加入;
                Object data = sharedQueue.poll(2, TimeUnit.SECONDS);


                if (null != data) {
                    System.out.println("consumed" + data);
                } else {
                    flag = false;
                }


            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
            }
        }
    }
}
